package com.yinhe.music.yhmusic.personal.modify;

import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.http.StatusCode;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ModifyPresenter extends BasePresenter<BaseModel, ModifyContract.IModifyView> implements ModifyContract.IModifyPresenter {
    @Override
    public void modifyImage(File file, int modifyType, String id) {
        if (getView() == null) {
            return;
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("mulitypart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("imageFile", file.getName(), requestBody);
        getView().showLoading();

        addSubscription(mModel.modifyUserImage(getModifyUrl(modifyType, id), filePart)
                .compose(schedulerProvider.applySchedulers())
                .subscribe(responseBody -> {
                    getView().hideLoading();
                    getView().updateImageUI();
                    getView().showToast("上传成功");
                }, throwable -> {
                    getView().hideLoading();
                    getView().showMessage(throwable);
                })
        );
    }

    @Override
    public void modifyInfo(int modifyType, String id, String nickName, String gender, String songMenuName) {
        addSubscription(mModel.modifyInfo(getModifyUrl(modifyType, id), nickName, gender, songMenuName)
                .compose(schedulerProvider.applySchedulers())
                .subscribe(baseInfo -> {
                    if (baseInfo.getCode() == StatusCode.CHANGE_DATA) {
                        getView().updateInfoUI();
                    }
                    getView().hideLoading();
                    getView().showToast(baseInfo.getMsg());
                }, throwable -> {
                    getView().hideLoading();
                    getView().showMessage(throwable);
                })
        );
    }

    private String getModifyUrl(int modifyType, String id) {
        String url;
        if (modifyType == IConstants.MODIFY_USER_INFO) {
            url = "/api/user";
        } else {
            url = "/api/user/" + "songMenu/" + id;
        }
        return url;
    }
}
